package org.jash.shop2111.net

import okhttp3.RequestBody
import retrofit2.Converter
import java.lang.StringBuilder
import java.lang.reflect.Array
import java.security.MessageDigest
import java.util.Arrays

class MyRequestBodyConverter<T>(val converter: Converter<T, RequestBody>?): Converter<T, RequestBody> {
    override fun convert(p0: T): RequestBody? {
        if (p0 is Map<*, *>) {
            val s = p0.values.map { it?.toString() }.reduce { s1, s2 -> s1 + s2 } ?: ""
            val chars = s.toCharArray()
            Arrays.sort(chars)
            val s1 = String(chars) + "tamboo"
            val md5 = MessageDigest.getInstance("MD5")
            val digest = md5.digest(s1.toByteArray())
            val sb = StringBuilder()
            for (b in digest) {
                sb.append(String.format("%02x", b))
            }
            (p0 as MutableMap<String, String>)["sign"] = sb.toString()
        }
        return converter?.convert(p0)
    }
}